#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t mutex;

char ch[2] = {0};

void *fun1(void *arg)
{
	int i = 0;
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(i % 2 == 0)
		{
			ch[0] = 'a';
			sleep(1);
			ch[1] = 'b';
		}else
		{
			ch[0] = 'c';
			sleep(1);
			ch[1] = 'd';
		}
		pthread_mutex_unlock(&mutex);

		i = i + 1;
		if(i > 10000) i = 0;

	}
}

void *fun2(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);

		printf("ch[0] = %c,ch[1] = %c\n",ch[0],ch[1]);

		pthread_mutex_unlock(&mutex);

		sleep(1);
	}

}

int main()
{

	pthread_t tid1 = 0,tid2 = 0;
	int ret = 0;

	pthread_mutex_init(&mutex,NULL);

	ret = pthread_create(&tid1,NULL,fun1,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}

	ret = pthread_create(&tid2,NULL,fun2,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	pthread_mutex_destroy(&mutex);

	return 0;

}





